package com.ccsu.joysport.service;

import com.ccsu.joysport.entity.Target;
import com.ccsu.joysport.repository.TargetRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class TargetService {
    @Autowired
    private TargetRepository targetRepository;

    public List<Target> getAllTargets() {
        return targetRepository.findAll();
    }

    public Target getTargetById(Long targetID) {
        return targetRepository.findById(targetID).orElse(null);
    }

    public Target createTarget(Target target) {
        return targetRepository.save(target);
    }

    public Target updateTarget(Long targetID, Target targetDetails) {
        Target target = targetRepository.findById(targetID).orElse(null);
        if (target != null) {
            target.setName(targetDetails.getName());
            target.setMinBmi(targetDetails.getMinBmi());
            target.setMaxBmi(targetDetails.getMaxBmi());
            target.setSuggestion(targetDetails.getSuggestion());
            return targetRepository.save(target);
        }
        return null;
    }

    public void deleteTarget(Long targetID) {
        targetRepository.deleteById(targetID);
    }

    public String getSuggestionByBmi(double heightCm, double weight) {
        // 将height从厘米转换为米
        double heightM = heightCm / 100.0;
        double bmi = weight / (heightM * heightM);
        List<Target> targets = targetRepository.findAll();
        for (Target target : targets) {
            if (bmi >= target.getMinBmi() && bmi <= target.getMaxBmi()) {
                return target.getSuggestion();
            }
        }
        return "No suggestion available for this BMI.";
    }
}

